package com.yupi.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.bizmq.BiMessageProducer;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.AIManager;
import com.yupi.springbootinit.manager.CosManager;
import com.yupi.springbootinit.manager.RedisLimiterManager;
import com.yupi.springbootinit.model.dto.chart.*;
import com.yupi.springbootinit.model.dto.file.UploadFileRequest;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.FileUploadBizEnum;
import com.yupi.springbootinit.model.vo.BIResponse;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AIManager aiManager;

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        // 参数校验
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<Chart>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion



    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        // 参数校验
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }


    @Resource
    private CosManager cosManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    private static final String systemContent =
            "你是一个数据分析师和前端开发专家";

    @Resource
    private BiMessageProducer biMessageProducer;

    /**
     * 智能分析业务
     *    同步执行
     * @param
     * @param
     * @param request
     * @return
     */
    @PostMapping("/genChartByAI")
    public BaseResponse<BIResponse> genChartByAI(@RequestPart("file") MultipartFile multipartFile,
                                             GenCharByAIRequest genCharByAIRequest, HttpServletRequest request) {
        String name = genCharByAIRequest.getName();
        String goal = genCharByAIRequest.getGoal();
        String charType = genCharByAIRequest.getCharType();
        //1.校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100
                ,ErrorCode.PARAMS_ERROR,"名称过长");
        //1.1校验文件
        // 1.1.1大小
        String originalFilename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB,ErrorCode.PARAMS_ERROR,"文件大小超过1MB");
        // 1.1.2后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffix = Arrays.asList("xls","xlsx");
        ThrowUtils.throwIf(!validFileSuffix.contains(suffix),ErrorCode.PARAMS_ERROR,"文件类型不符合");
        User loginUser = userService.getLoginUser(request);
        // 1.2 限流判断，每个用户一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());

        //2.拼接用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("{").append(goal).append("}").append("\n");
        //2.1读取用户上传的文件
        //并且进行数据压缩
        String excellToCsv = ExcelUtils.excellToCsv(multipartFile);
        //2.2以下是AI问答业务
        userInput.append("图表格式：").append("{").append(charType).append("}").append("\n");
        userInput.append("原始数据：").append("{").append(excellToCsv).append("}").append("\n");
        userInput.append("请根据输入内容，按照以下指定格式生成内容（此外不要输出任何多余的开头、结尾）\n" +
                "=====\n" +
                "{按照分析需求进行数据可视化，生成前端 Echarts V5 的 option 配置对象JSON代码，代码内不要有注释，所有代码都应放在option配置对象里，不要使用Markdown格式输出代码，直接以文本格式输出代码}\n" +
                "=====\n" +
                "{明确的数据分析结论、越详细越好，不要生成多余的注释}" +
                "在你给出前端代码和数据分析结论之间都先打印一行=====");
        //2.3 拼接分析目标和图表类型
        String AIResult = aiManager.AIChat(systemContent, userInput.toString());
        String[] split = AIResult.split("=====");
        if(split.length < 3){
            //throw new BusinessException(ErrorCode.SYSTEM_ERROR,"AI 生成错误");
            log.error("AI生成错误");
            //除去option =
            String searchString0 = "option = ";
            int index0 = AIResult.indexOf(searchString0);
            if(index0 != -1){
                AIResult = AIResult.substring(index0 + searchString0.length());
            }
            String genChart;
            String genResult;
            String[] split2 = AIResult.split("```");
            if(split2.length >= 2){
                String searchString = "javascript";
                int index = split2[1].indexOf(searchString);
                if(index != -1){
                    split2[1] = split2[1].substring(index + searchString.length());
                }
                genResult = split2.length == 2 ? null : split2[2];
                genChart = split2[1];
            } else {
                genResult = AIResult;
                genChart = AIResult;
            }
            BIResponse biResponse = new BIResponse();
            biResponse.setGenChart(genChart);
            biResponse.setGenResult(genResult);
            Long chartId = toChart(name, loginUser.getId(), goal, excellToCsv, charType, genChart, genResult);
            createDataTable(multipartFile, chartId);
            return ResultUtils.success(biResponse);
        }
        String genChart = split[1];
        String genResult = split[2];
        //2.4对genChart进行处理
        //除去option =
        String searchString = "option = ";
        int index = genChart.indexOf(searchString);
        if(index != -1){
            genChart = genChart.substring(index + searchString.length());
        }
        //除去 ```javascript```
        String[] splitWithoutPoint = genChart.split("```");
        if(splitWithoutPoint.length >= 2){
            searchString = "javascript";
            index = splitWithoutPoint[1].indexOf(searchString);
            if(index != -1){
                genChart = splitWithoutPoint[1].substring(index + searchString.length());
            }
        }
        BIResponse biResponse = new BIResponse();
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);
        //3.1存入数据库
        Long chartId = toChart(name, loginUser.getId(), goal, excellToCsv, charType, genChart, genResult);
        //3.2对文件内容动态数据建表
        createDataTable(multipartFile, chartId);
        return ResultUtils.success(biResponse);
    }

    /**
     * 智能分析业务
     *    使用线程池异步执行
     * @param
     * @param
     * @param request
     * @return
     */

    @PostMapping("/genChartByAI/async")
    public BaseResponse<BIResponse> genChartByAIAsync(@RequestPart("file") MultipartFile multipartFile,
                                                 GenCharByAIRequest genCharByAIRequest, HttpServletRequest request) {
        String name = genCharByAIRequest.getName();
        String goal = genCharByAIRequest.getGoal();
        String charType = genCharByAIRequest.getCharType();
        //1.校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100
                ,ErrorCode.PARAMS_ERROR,"名称过长");
        //1.1校验文件
        // 1.1.1大小
        String originalFilename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB,ErrorCode.PARAMS_ERROR,"文件大小超过1MB");
        // 1.1.2后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffix = Arrays.asList("xls","xlsx");
        ThrowUtils.throwIf(!validFileSuffix.contains(suffix),ErrorCode.PARAMS_ERROR,"文件类型不符合");
        User loginUser = userService.getLoginUser(request);
        // 1.2 限流判断，每个用户一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());

        //2.拼接用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("{").append(goal).append("}").append("\n");
        //2.1读取用户上传的文件
        //并且进行数据压缩
        String excellToCsv = ExcelUtils.excellToCsv(multipartFile);
        //2.2以下是AI问答业务  2.3 拼接分析目标和图表类型
        userInput.append("图表格式：").append("{").append(charType).append("}").append("\n");
        userInput.append("原始数据：").append("{").append(excellToCsv).append("}").append("\n");
        userInput.append("请根据输入内容，按照以下指定格式生成内容（此外不要输出任何多余的开头、结尾）\n" +
                "=====\n" +
                "{按照分析需求进行数据可视化，生成前端 Echarts V5 的 option 配置对象JSON代码，代码内不要有注释，所有代码都应放在option配置对象里，不要使用Markdown格式输出代码，直接以文本格式输出代码}\n" +
                "=====\n" +
                "{明确的数据分析结论、越详细越好，不要生成多余的注释}" +
                "在你给出前端代码和数据分析结论之间都先打印一行=====");
        //3.存入数据库
        //3.1存入数据库
        Long chartId = toChart(name, loginUser.getId(), goal, excellToCsv, charType);
        //3.2对文件内容动态数据建表
        createDataTable(multipartFile, chartId);

        //4.接收AI回答 --- 线程池
        CompletableFuture.runAsync(() -> {
            //0.改变图表生成状态为running
            Chart updateChart = new Chart();
            updateChart.setId(chartId);
            updateChart.setStatus("running");
            boolean b = chartService.updateById(updateChart);
            ThrowUtils.throwIf(!b,ErrorCode.SYSTEM_ERROR,"图表正在生成状态保存失败");

            //1.调用AI
            String AIResult = aiManager.AIChat(systemContent, userInput.toString());
            //2.生成返回结果
            String genChart;
            String genResult;
            String[] split = AIResult.split("=====");
            if(split.length < 3){
                log.error("AI生成错误");
                //除去option =
                String searchString0 = "option = ";
                int index0 = AIResult.indexOf(searchString0);
                if(index0 != -1){
                    AIResult = AIResult.substring(index0 + searchString0.length());
                }
                String[] split2 = AIResult.split("```");
                if(split2.length >= 2){
                    String searchString = "javascript";
                    int index = split2[1].indexOf(searchString);
                    if(index != -1){
                        split2[1] = split2[1].substring(index + searchString.length());
                    }
                    genResult = split2.length == 2 ? null : split2[2];
                    genChart = split2[1];
                } else {
                    genResult = AIResult;
                    genChart = AIResult;
                }
            } else {
                genChart = split[1];
                genResult = split[2];
                //2.4对genChart进行处理
                //除去option =
                String searchString = "option = ";
                int index = genChart.indexOf(searchString);
                if(index != -1){
                    genChart = genChart.substring(index + searchString.length());
                }
                //除去 ```javascript```
                String[] splitWithoutPoint = genChart.split("```");
                if(splitWithoutPoint.length >= 2){
                    searchString = "javascript";
                    index = splitWithoutPoint[1].indexOf(searchString);
                    if(index != -1){
                        genChart = splitWithoutPoint[1].substring(index + searchString.length());
                    }
                }
            }
            // 3.将AI生成结果写入数据库
            Chart resultChart = new Chart();
            resultChart.setId(chartId);
            resultChart.setStatus("succeed");
            resultChart.setGenChart(genChart);
            resultChart.setGenResult(genResult);
            boolean update = chartService.updateById(resultChart);
            ThrowUtils.throwIf(!update,ErrorCode.SYSTEM_ERROR,"图表生成成功状态保存失败");
        },threadPoolExecutor);


        BIResponse biResponse = new BIResponse();
        return ResultUtils.success(biResponse);
    }

    /**
     * 智能分析业务
     *    使用消息队列异步执行
     * @param
     * @param
     * @param request
     * @return
     */

    @PostMapping("/genChartByAI/async/mq")
    public BaseResponse<BIResponse> genChartByAIAsyncMq(@RequestPart("file") MultipartFile multipartFile,
                                                      GenCharByAIRequest genCharByAIRequest, HttpServletRequest request) {
        String name = genCharByAIRequest.getName();
        String goal = genCharByAIRequest.getGoal();
        String charType = genCharByAIRequest.getCharType();
        //1.校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100
                ,ErrorCode.PARAMS_ERROR,"名称过长");
        //1.1校验文件
        // 1.1.1大小
        String originalFilename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB,ErrorCode.PARAMS_ERROR,"文件大小超过1MB");
        // 1.1.2后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffix = Arrays.asList("xls","xlsx");
        ThrowUtils.throwIf(!validFileSuffix.contains(suffix),ErrorCode.PARAMS_ERROR,"文件类型不符合");
        User loginUser = userService.getLoginUser(request);
        // 1.2 限流判断，每个用户一个限流器
        redisLimiterManager.doRateLimit("genChartByAi_" + loginUser.getId());
        //2.1读取用户上传的文件
        //并且进行数据压缩
        String excellToCsv = ExcelUtils.excellToCsv(multipartFile);
        //3.存入数据库
        //3.1存入数据库
        Long chartId = toChart(name, loginUser.getId(), goal, excellToCsv, charType);
        //3.2对文件内容动态数据建表
        createDataTable(multipartFile, chartId);

        //4.接收AI回答 --- 放入消息队列
        //todo 建设处理任务队列满了后，抛异常
        biMessageProducer.sendMessage(String.valueOf(chartId));

        BIResponse biResponse = new BIResponse();
        return ResultUtils.success(biResponse);
    }


    private void createDataTable(@RequestPart("file") MultipartFile multipartFile, Long chartId) {
        //动态数据建表
        List<String> header = ExcelUtils.excelGetHeader(multipartFile);
        List<List<String>> excelGetData = ExcelUtils.excelGetData(multipartFile);
        chartService.createTable(chartId, header);
        for (List<String> excelGetDatum : excelGetData) {
            chartService.insertTable(chartId, excelGetDatum.subList(0, header.size()));
        }
    }

    private Long toChart(String name,Long id,String goal,String excellToCsv,String charType,String genChart,String genResult){
        //存入数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setUserId(id);
        chart.setGoal(goal);
        chart.setCharData(excellToCsv);
        chart.setCharType(charType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setStatus("succeed");
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表保存失败");
        //返回表格的id
        return chart.getId();
    }

    private Long toChart(String name,Long id,String goal,String excellToCsv,String charType){
        //存入数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setUserId(id);
        chart.setGoal(goal);
        chart.setCharData(excellToCsv);
        chart.setCharType(charType);
        chart.setStatus("wait");
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表保存失败");
        //返回表格的id
        return chart.getId();
    }


    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }








}
